import type { RequestParams } from "@/api";
import SearchForm from "@/components/SearchForm";
import St from "@/components/St";
import type {
	StColumnsType,
	StRef,
} from "@/components/St/types";
import type {
	BaseSearchModel,
	ListModel,
	ListSearchModel,
	PagedListSearchModel,
} from "@/types";
import { useRef } from "react";
import { ModalBody, ModalContent, ModalFooter } from "../content";
import { useModalRef } from "../hook";

interface SelectModalProps<
	TModel = unknown,
	TSearch extends BaseSearchModel | undefined = undefined,
> {
	multiple?: boolean;
	selectedKeys?: (string | number)[];
	data:
	| TModel[]
	| ListModel<TModel>
	| ((
		req: ListSearchModel<TSearch> | PagedListSearchModel<TSearch>,
		params?: RequestParams,
	) => Promise<TModel[] | Partial<ListModel<TModel>>>);
	columns: StColumnsType<TModel>;
}

export default function SelectModal<
	TModel,
	TSearch extends BaseSearchModel | undefined = undefined,
>({
	multiple,
	selectedKeys,
	data,
	columns,
}: SelectModalProps<TModel, TSearch>) {
	const okDisabled = !selectedKeys || selectedKeys.length === 0;
	const buttonText = {
		ok: "确定",
		cancel: "取消",
	};

	const stRef = useRef<StRef<TModel>>(null);

	const modalRef = useModalRef();

	const handleOk = () => {
		const selectedRows = stRef.current?.getSelectedRows() ?? [];
		if (multiple) {
			const selectedData = selectedRows.filter((x) => x !== undefined);
			modalRef.close(selectedData);
		} else {
			modalRef.close(selectedRows[0]);
		}
	};

	const handleCancel = () => {
		modalRef.close();
	};

	return (
		<ModalContent>
			<ModalBody>
				<SearchForm showReset />
				<St
					ref={stRef}
					columns={columns}
					data={data}
					rowSelection={multiple ? "checkbox" : "radio"}
					selectedKeys={selectedKeys}
				/>
			</ModalBody>
			<ModalFooter
				okText={buttonText.ok}
				cancelText={buttonText.cancel}
				okDisabled={okDisabled}
				onOk={handleOk}
				onCancel={handleCancel}
			/>
		</ModalContent>
	);
}
